import { CommandDialog } from '@amcax/base';
import { i18n, nmAppErrorLog } from '@app-nextmesh/common/utils';
import { showLoading } from '@app-nextmesh/components';
import { documentV2 } from '@app-nextmesh/domain';
import { useProjectStore } from '@app-nextmesh/store/project';
import {
  IResult,
  ISolve,
  ModelEventType,
  VisualType,
} from '@app-nextmesh/types';
import { events, updateModelsVisible } from '@app-nextmesh/utils';
import { deleteModels, renderModels } from '@app-nextmesh/utils/renderModel';
import { Col, Row, Select, Table, TableProps } from 'antd';
import { cloneDeep } from 'lodash';
import React, { useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import { IProps } from './types';
interface IParams {
  step: number;
  frame?: number;
  layer?: string;
  fieldName?: string;
  variableName?: string;
  error?: string;
}

interface DataType {
  key: React.Key;
  frame: string;
}

const WrapperStyle = styled.div`
  row-gap: 8px;
  width: 410px;
  padding: 0 20px 0 20px;
  padding-bottom: 8px;
  display: flex;
  flex-direction: column;

  .form-dialog_footer {
    width: 100%;
    padding: 8px 0 12px !important;
  }
`;

export default function TaskResultForm({ data: initData, onClose }: IProps) {
  const projectInfo = useProjectStore((state) => state.projectInfo);
  const [data, setData] = useState<IResult>(null); // 记录组件初始数据
  const [solves, setSolves] = useState<Array<ISolve>>([]); // 记录场结果所有数据
  const [fieldData, setFieldData] = useState([]); // 记录场数据
  const [fieldType, setFieldType] = useState(null); // 记录field类型数据
  const [framesData, setFramesData] = useState([]); // 记录框架数据
  const [columnsData, setColumnsData] = useState([]); // 获取表格动态头部
  const [variableData, setVariableData] = useState([]); // 记录可变因素数据
  // const [layerData, setLayerData] = useState([]); // 记录上表面或下表面数据
  const [params, setParams] = useState<IParams>(undefined); // 记录选择Step, Filed,Frames 变化的数据
  const resultMeshesId = useRef<string[]>([]); // 保存结果的网格id,用于在关闭窗口时,清除这些网格

  useEffect(() => {
    // 隐藏场景中的全部几何和网格,方便看结果的网格
    updateModelsVisible('hide');
    // 设置colormap
    events.emit(ModelEventType.SetColormap, 'jet');
    return () => {
      // 重置colormap
      events.emit(ModelEventType.SetColormap, null);
      // 删除结果的网格
      deleteModels(resultMeshesId.current);

      // 显示场景中的全部几何和网格
      updateModelsVisible('show');
    };
  }, []);
  useEffect(() => {
    const newData = cloneDeep(initData.formData);
    setData(newData);
    resultRenderData(newData.uuid);
    getTaskResultInfo(newData.uuid);
  }, [initData.formData]);
  const resultRenderData = async (uuid: string) => {
    const data = await documentV2.resultRenderData(uuid);
    resultMeshesId.current = data?.map((d) => d.id) ?? [];
    await renderModels(data, true, false);
  };
  const getTaskResultInfo = (taskId: string) => {
    const hide = showLoading();
    documentV2
      .resultInfo(taskId)
      .then((rspData) => {
        if (rspData.solve?.length > 0) {
          setSolves(rspData.solve);
          const solveLast: any = rspData.solve.slice(-1)[0];
          const newParams: IParams = { step: solveLast.step };
          const framesList = solveLast.frames.map((item, index) => {
            return { ...item, key: index };
          });
          setFramesData(framesList);
          // 提取所有唯一的字段名作为表头
          const allKeys = framesList.reduce((acc, item) => {
            return [...acc, ...Object.keys(item)];
          }, []);
          // 去重
          const uniqueKeys = [...new Set(allKeys)].filter(
            (item) =>
              item !== 'field_data' && item !== 'key' && item !== 'lsdvmn',
          );
          // 根据字段名生成表头
          const columns = uniqueKeys.map((key: any) => ({
            title: key.toUpperCase(), // 使用字段名作为表头
            dataIndex: key, // 数据中的键
            key: key, // 唯一标识
            width: 30,
          }));
          if (framesList.length !== 0) {
            newParams.frame = framesList.slice(-1)[0].frame;
          }
          setFramesData(framesList);
          setColumnsData(columns);
          if (solveLast.field?.length > 0) {
            newParams.fieldName = solveLast.field.slice(-1)[0].name;
            setFieldData(solveLast.field);
            setVariableData(solveLast.field.slice(-1)[0].Variable);
            setFieldType(solveLast.field.slice(-1)[0].type);
            const newData = cloneDeep(initData.formData);
            if (solveLast.field.slice(-1)[0].layer) {
              const uniqueLayers: any[] = [
                ...new Set(solveLast.field.slice(-1)[0].layer),
              ];
              newParams.layer = uniqueLayers[0];
            }
            solveLast.field.forEach((item) => {
              if (item.name === newParams.fieldName) {
                if (item.Variable.slice(-1)[0] !== 'value') {
                  newParams.variableName = item.Variable.slice(-1)[0];
                }
              }
            });
            changeField(newData, newParams);
          }
          setParams(newParams);
        }
      })
      .catch((error) => {
        nmAppErrorLog('TaskResultForm getTaskResultInfo', error);
      })
      .finally(() => hide());
  };
  const changeField = (data: IResult, params: IParams) => {
    if (params?.fieldName) {
      events.emit(
        ModelEventType.LoadingField,
        VisualType.Simulation,
        data.uuid,
        params,
        false,
      );
    }
  };

  const selectInit: any = (array: [], type: string) =>
    array.map((item) => ({
      label: type ? item[type] : item,
      value: type ? item[type] : item,
    }));

  const rowSelection: TableProps<DataType>['rowSelection'] = {
    type: 'radio', // 设置为 'radio' 实现单选
    selectedRowKeys: [params?.frame],
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      const newParams = {
        ...params,
        frame: Number(selectedRows[0].frame),
      };
      setParams(newParams);
      changeField(data, newParams);
    },
  };

  return (
    <CommandDialog
      title={i18n.t('result')}
      placement='topLeft'
      onClose={onClose}>
      <WrapperStyle>
        <Row>
          <Col span={4}>Step:</Col>
          <Col span={16}>
            <Select
              disabled={projectInfo.readonly}
              style={{ width: 150 }}
              onChange={(value) => {
                const step = parseInt(value as string);
                const newParams = {
                  step,
                  fieldName: undefined,
                };
                solves.forEach((item: any) => {
                  if (item.step === step) {
                    setFieldData(item.field);
                  }
                });
                setParams(newParams);
              }}
              value={params?.step !== undefined ? params.step + '' : undefined}
              options={selectInit(solves, 'step')}
            />
          </Col>
        </Row>
        <Row>
          <Col span={4}>Field:</Col>
          <Col span={10}>
            <Select
              disabled={projectInfo.readonly}
              style={{ width: 150 }}
              onChange={(value) => {
                const newParams = {
                  ...params,
                  fieldName: value,
                  variableName: undefined,
                };
                let type = '';
                fieldData.forEach((item) => {
                  if (item.name === value) {
                    setVariableData(item.Variable);
                    type = item.type;
                  }
                });
                setFieldType(type);
                if (type === 'scalar') {
                  delete newParams.variableName;
                  changeField(data, newParams);
                }
                setParams(newParams);
              }}
              value={
                params?.fieldName !== undefined ? params.fieldName : undefined
              }
              options={selectInit(fieldData, 'name')}
            />
          </Col>
          {fieldType !== 'scalar' && (
            <Col span={10}>
              <Select
                disabled={projectInfo.readonly}
                style={{ width: 100 }}
                onChange={(value) => {
                  const newParams = {
                    ...params,
                    variableName: value,
                  };
                  setParams(newParams);
                  setParams(newParams);
                  changeField(data, newParams);
                }}
                value={
                  params?.variableName !== undefined
                    ? params.variableName
                    : undefined
                }
                options={selectInit(variableData, undefined)}
              />
            </Col>
          )}
        </Row>
        {/*{layerData.length !== 0 && (
          <Row>
            <Col span={4}>Layer:</Col>
            <Col span={16}>
              <Select
                disabled={projectInfo.readonly}
                style={{ width: 150 }}
                onChange={(value) => {
                  const newParams = {
                    ...params,
                    layer: value,
                  };
                  setParams(newParams);
                  changeField(data, newParams);
                }}
                value={
                  params?.layer !== undefined ? params.layer + '' : undefined
                }
                options={selectInit(layerData)}
              />
            </Col>
          </Row>
        )}*/}
        <div style={{ width: '100%', margin: '0 auto' }}>
          <Row>
            <Col span={12}>Frames:</Col>
          </Row>
          <Table
            rowSelection={rowSelection}
            dataSource={framesData}
            pagination={false}
            columns={columnsData}
            scroll={{ x: 'auto' }}
          />
        </div>
      </WrapperStyle>
    </CommandDialog>
  );
}
